package com.ayitubie.refuelweb.controller;

import com.ayitubie.refuelweb.minio.MinioTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/minio")
public class MinioFile {
    @Autowired
    private MinioTemplate minioTemplate;

    @RequestMapping(value = "/getFile",method = RequestMethod.GET)
    public void getFile(HttpServletResponse response, @RequestParam(required = false, defaultValue = "") String bucketName, @RequestParam(required = false, defaultValue = "") String objectName) throws Exception {
        ServletOutputStream out = null;
        ByteArrayOutputStream baos = null;
        try {
            InputStream inStream = minioTemplate.downloadFile(bucketName, objectName);
            byte[] buffer = new byte[1024];
            int len;
            baos = new ByteArrayOutputStream();
            while ((len = inStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            out = response.getOutputStream();
            out.write(baos.toByteArray());
        } catch (Exception e) {
            log.error("minio读取文件错误：{},仓库名:{},文件名:{}",e,bucketName,objectName);
        } finally {
            Objects.requireNonNull(baos).flush();
            baos.close();
            Objects.requireNonNull(out).flush();
            out.close();
        }

    }

    @PostMapping("/upload")
    @ResponseBody
    public String minioUpload(@RequestParam(value = "file", required = true) MultipartFile file,HttpServletResponse response) {
        String fileName = null;
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String fileName_origin = file.getOriginalFilename();
            String contentType = file.getContentType();
            fileName = minioTemplate.uploadFile(inputStream,"mahuaide",fileName_origin,contentType);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileName;
    }

    @PostMapping("/uploadChunk")
    @ResponseBody
    public void minioUploadChunk(@RequestParam("file") MultipartFile file,
                                   @RequestParam("fileName") String fileName,
                                   @RequestParam("chunkIndex") int chunkIndex,
                                   @RequestParam("totalChunks") int totalChunks) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        if (fileName == null || fileName.trim().isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        if (chunkIndex < 0 || chunkIndex >= totalChunks) {
            throw new IllegalArgumentException("无效的分块索引");
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String fileNameChunk = "/chunk/" + fileName + "_" + chunkIndex;
            String contentType = file.getContentType();
            fileNameChunk = minioTemplate.uploadFile(inputStream,"mahuaide",fileNameChunk,contentType);
            // 最后一个切片上传完以后，合并文件
            if(chunkIndex == totalChunks -1){
                minioTemplate.mergeChunks(fileName, totalChunks,"mahuaide",contentType);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(inputStream != null){}
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
